﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace ZPod.MTG.Windows
{
	public class FormFreezer : IDisposable
	{
		#region Private Properties
		
		Form _form;
		PictureBox _pictureBox;
		int _freezeCount = 0;
		
		#endregion

		#region Public Properties
		
		public bool IsFrozen
		{
			get { return (_freezeCount > 0); }
		}

		#endregion

		#region Public Constructors

		public FormFreezer(Form form)
			: this(form, true)
		{
		}
		
		public FormFreezer(Form form, bool freezeIt)
		{
			this._form = form;
			if (freezeIt) this.Freeze();
		}

		#endregion

		#region Public Methods

		public void Freeze()
		{
			if (++_freezeCount > 1)
			{
				return;
			}

			_pictureBox = new PictureBox();
			_pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;

			Graphics frmGraphics = _form.CreateGraphics();
			Rectangle rect = _form.ClientRectangle;
			_pictureBox.Image = new Bitmap(rect.Width, rect.Height, frmGraphics);
			frmGraphics.Dispose();

			Graphics picGraphics = Graphics.FromImage(_pictureBox.Image);
			picGraphics.CopyFromScreen(_form.PointToScreen(new Point(rect.Left, rect.Top)), new Point(0, 0), new Size(rect.Width, rect.Height));
			picGraphics.Dispose();

			_form.Controls.Add(_pictureBox);
			_pictureBox.BringToFront();
		}

		public void Unfreeze(bool force)
		{
			// exit if nothing to unfreeze
			if (_freezeCount == 0)
				return;
			// remember we've unfrozen the form, but exit if it is still frozen
			_freezeCount -= 1;
			// force the unfreeze if so required
			if (force)
				_freezeCount = 0;
			if (_freezeCount > 0)
				return;
			// remove the picture box control and clean up
			_pictureBox.Controls.Remove(_pictureBox);
			_pictureBox.Dispose();
			_pictureBox = null;
		}

		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
			this.Unfreeze(true);
		}

		#endregion
	}
}
